import 'dart:convert';
import 'dart:io';

import 'package:flutter/services.dart';
const methodChannel = const MethodChannel('samples.flutter.dev/test');


const String webAddressApi = '192.168.2.126';

Map UserData = {
  "nickname":"",
  "id":0,
};

Map dailyList = {"data":[]};


class ajax{
  static Future<Map> postToken({ required String path,Map? body}) async{
    final String token =  await methodChannel.invokeMethod('getSharedPreferences','token');

    return post(path:path,body:body,header: {
      "Authorization":token
    });
  }

  static Future<Map> post({ required String path,Map? body,Map? header}) async{

    final client = HttpClient();
    final uri = Uri.parse('http://'+webAddressApi+path);
    final request = await client.postUrl(uri);

    // 添加HTTP头部信息，如内容类型
    request.headers.set('content-type', 'application/json');
    if(header != null){
      for (var key in header.keys) {
        request.headers.set(key, header[key]);
      }
    }

    if(body != null){
      // 设置请求体
      request.add(utf8.encode(json.encode(body)));
    }


    // 发送请求并获取响应
    final response = await request.close();


    //读取响应内容
    String _text = await response.transform(utf8.decoder).join();
    //输出响应头
    //print(response.statusCode);
    //print(_text);

    //关闭client后，通过该client发起的所有请求都会终止。
    client .close();

    return {
      "statusCode":response.statusCode,
      "body":_text
    };
  }
}